package com.zdb.personal.controller;


import com.zdb.personal.service.SendSmsService;
import io.netty.util.internal.StringUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * sms短信验证
 */
@RestController
@RequestMapping("/sms")
//@CrossOrigin 跨域支持
public class SmsApiController {
    @Resource
    private SendSmsService sendSms;

    @Resource
    private RedisTemplate<String,String> redisTemplate;

    @RequestMapping("/send/{phone}")
    private String code(@PathVariable("phone") String phone){
        //调用发送方法，(模拟真实业务 redis)

        String code = this.redisTemplate.opsForValue().get(phone);
        System.err.println(code);
        if(!StringUtil.isNullOrEmpty(code)){
            System.err.println(StringUtil.isNullOrEmpty(code));
            return "手机号："+phone+":"+code+"已存在，还没过期";
        }
        //生成验证码并存储到redis中
        code = UUID.randomUUID().toString().substring(0, 4);
        HashMap<String, Object> param = new HashMap<>();
        param.put("code",code);
        System.err.println(param);

        //传入调用的sms
        boolean isSend = sendSms.send(phone, "SMS_200691164", param);
        if(isSend){
            this.redisTemplate.opsForValue().set(phone,code,5, TimeUnit.SECONDS); //存入redis 设置五分钟过期
            return "发送成功"+",验证码:"+code;
        }else {
            return "发送失败";
        }

    }



}
